import { login, getInfo, teacherLogin, getTeacherInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  id: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    // 深度拷贝原始数据
    let rawRoles = JSON.parse(JSON.stringify(roles || []));

    // 处理单角色情况
    if (!Array.isArray(rawRoles)) {
      rawRoles = [rawRoles];
    }

    // 规范化处理
    const normalizedRoles = rawRoles.map(role => {
      if (typeof role === 'object') {
        role = role.roleName || role.name || '';
      }
      return String(role).toLowerCase();
    }).filter(role => role);

    // 确定主角色
    let primaryRole = '';
    if (normalizedRoles.includes('admin') || normalizedRoles.some(r => r.includes('管理员'))) {
      primaryRole = 'admin';
    } else if (normalizedRoles.includes('teacher') || normalizedRoles.some(r => r.includes('讲师'))) {
      primaryRole = 'teacher';
    } else if (normalizedRoles.length > 0) {
      primaryRole = normalizedRoles[0];
    } else {
      console.warn('使用默认角色');
      primaryRole = 'default';
    }

    state.roles = normalizedRoles;
    state.role = primaryRole;

    console.log('角色状态已更新', {
      source: rawRoles,
      stored: state.roles,
      primaryRole: state.role
    });
  },

  // 重置状态时保留角色信息
  resetToken(state) {
    state.token = '';
    state.id = '';
    state.roles = [];
    state.role = '';
  },
  SET_ID: (state, id) => {
    state.id = id
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      const { username, password, type } = userInfo
      const loginAction = type === 'admin' ? login : teacherLogin
      loginAction(username.trim(), password).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息（管理员）
  GetInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        try {
          console.log('完整用户信息响应:', JSON.parse(JSON.stringify(response)));

          if (!response || !response.data) {
            throw new Error('响应数据格式错误');
          }

          const { roles, buttons, name, avatar, id } = response.data;

          // 空值检查
          if (!roles) {
            throw new Error('角色信息不存在');
          }

          // 提交前验证
          const originalRoles = JSON.parse(JSON.stringify(roles));
          commit('SET_ROLES', originalRoles);

          // 提交后验证
          if (!state.roles || state.roles.length === 0) {
            throw new Error('角色信息未存入Vuex');
          }

          commit('SET_BUTTONS', buttons);
          commit('SET_NAME', name || '');
          commit('SET_AVATAR', avatar || '');
          commit('SET_ID', id || '');

          resolve(response.data);
        } catch (error) {
          console.error('处理用户信息时出错:', error);
          // 保留当前token但标记为需要重新验证
          commit('SET_ROLES', ['need-recheck']);
          reject(error);
        }
      }).catch(error => {
        console.error('获取用户信息失败:', error);
        commit('SET_ROLES', ['error']);
        reject(error);
      });
    });
  },
  // 获取讲师信息
  GetTeacherInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getTeacherInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('验证失败，请重新登录。')
        }
        const { roles, name, avatar, id } = data
        if (!roles || roles.length === 0) {
          reject('getInfo: 角色不能为空!')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_ID', id)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户登出
  logout({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', []) // 清空角色数组
      removeToken()
      resolve()
    })
  },

  // 移除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', []) // 清空角色数组
      commit('SET_ID', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
